How To Work with Arrays in Ruby

您所在的位置:网站首页 ruby indexof How To Work with Arrays in Ruby

How To Work with Arrays in Ruby

2023-08-15 22:21| 来源: 网络整理| 查看: 265

Tutorial Series: How To Code in Ruby1/11 How To Install Ruby and Set Up a Local Programming Environment on Ubuntu 22.04 2/11 How To Install Ruby on Rails with rbenv on Ubuntu 22.04 3/11 How To Write Your First Ruby Program 4/11 How To Use IRB to Explore Ruby 5/11 How To Use Comments in Ruby 6/11 Understanding Data Types in Ruby 7/11 How To Work with Strings in Ruby 8/11 How To Work with String Methods in Ruby 9/11 How To Work with Arrays in Ruby 10/11 How To Use Array Methods in Ruby 11/11 How To Convert Data Types in Ruby // Tutorial //How To Work with Arrays in RubyPublished on October 6, 2017 · Updated on January 26, 2023RubyDevelopmentDefault avatar

By Brian Hogan and Tony Tran

How To Work with Arrays in RubyIntroduction

An array is a data structure that represents a list of values, called elements. Arrays let you store multiple values in a single variable. In Ruby, arrays can contain any data type, including numbers, strings, and other Ruby objects. This can condense and organize your code, making it more readable and maintainable. All arrays are objects with their own methods you can call, providing a standardized way to work with datasets.

In this tutorial, you’ll create arrays, access the values they contain, add, modify, and remove elements in an array, and iterate through the elements in an array to solve more complex problems.

Creating an Array

You’ll start by looking at how to create arrays in more detail. As an example, here is a list of various shark species. Without an array, you might store them in individual variables:

sharks.rb shark1 = "Hammerhead" shark2 = "Great White" shark3 = "Tiger"

This approach is verbose and can quickly become difficult to maintain, as it’s not very flexible. Adding another shark means you’d have to add, and track, an additional variable.

If you use an array, you can simplify this data. To create an array in a Ruby program, use square brackets: ([]), and separate the values you want to store with commas:

sharks.rb sharks = ["Hammerhead", "Great White", "Tiger"]

Instead of creating three separate variables, you now have one variable that contains all three sharks. In this example, you used square brackets — [] — to create an array, and separated each entry with a comma. If you had to add an additional shark, you would add another shark to the array rather than creating and managing a new variable.

You can print out an entire array with the print statement, which will display the array’s contents:

print sharks Output["Hammerhead", "Great White", "Tiger"]

If you want to create an array where each entry is a single word, you can use the %w{} syntax, which creates a word array:

days = %w{Monday Tuesday Wednesday Thursday Friday Saturday Sunday}

This is equivalent to creating the array with square braces:

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

However, notice that the %w{} method lets you skip the quotes and the commas.

Arrays are often used to group together lists of similar data types, but in Ruby, arrays can contain any value or a mix of values. This includes other arrays. Here’s an example of an array that contains a string, a nil value, an integer, and an array of strings:

mixed_data.rb record = [ "Sammy", null, 7, [ "another", "array", ] ]

Now you’ll look at how to access data stored in arrays.

Accessing Items in Arrays

To access a specific item, or element of an array, you reference its index, or its position in the array. In Ruby, indexes start at zero. In order to retrieve the first element from your sharks array, you append the element’s index to the variable using square brackets:

sharks.rb sharks = ["Hammerhead", "Great White", "Tiger"]

The sharks array has three elements. Here is a breakdown of how each element in the sharks array is indexed.

Hammerhead Great White Tiger 0 1 2

The first element in the array is Hammerhead, which is indexed at 0. The last element is Tiger, which is indexed at 2. Counting starts with 0 in indices, which goes against the natural intuition to start counting at 1, so you’ll want to keep this in mind until it becomes natural.

Note: It might help you to think of the index as an offset, meaning the number of places from the start of the array. The first element is at the beginning, so its offset, or index, is 0. The second element is one spot away from the first entry in the array, so its offset, or index, is 1.

You can find out how many elements are in an array with the length method:

sharks.length Output3

Although the indices of sharks start at 0 and go to 2, the length property returns the number of elements in the array, which is 3. It’s not concerned with the indices at all.

If you wanted to find out the index number of a specific element in an array, such as Tiger, use the index() method:

print sharks.index("Tiger") Output2

This returns the index of the first element containing that text. If an index number is not found, such as for a value that does not exist, the console will return nil:

print sharks.index("Whale") Outputnil

To get the last element of an array in Ruby, use the index -1:

print sharks[-1] Output"Tiger"

Ruby also provides the first and last methods to get the first and last elements without using indices:

puts sharks.first puts sharks.last Output"Hammerhead" "Tiger"

Attempting to access an index that doesn’t exist will return nil:

sharks[10] Outputnil

Arrays can contain other arrays, which are called nested arrays. This is one way to model two-dimensional datasets in a program. Here’s an example of a nested array:

nested_array = [ [ "salmon", "halibut", ], [ "coral", "reef", ] ]

In order to access elements in a nested array, you would add another index number to correspond to the inner array. For example, to retrieve the value coral from this nested array, you’d use the following statement:

print nested_array[1][0]; Outputcoral

In this example, you accessed the array at position 1 of the nested_array variable, which returned the array ["coral", "reef"]. You then accessed the elements at position 0 of that array, which was "coral".

Now you’ll look at how to add elements to an array.

Adding Elements to Arrays

You have three elements in your sharks array, which are indexed from 0 to 2:

sharks.rb sharks = ["Hammerhead", "Great White", "Tiger"]

There are a few ways to add a new element. You could assign a value to the next index, which in this case would be 3:

sharks[3] = "Whale"; print sharks Output["Hammerhead", "Great White", "Tiger", "Whale"]

This method is error-prone though. If you add an element and accidentally skip an index, it will create a nil element in the array.

sharks[5] = "Sand"; print sharks; Output["Hammerhead", "Great White", "Tiger", "Whale", nil, "Sand"]

Attempting to access the extra array element will return its value, which will be nil:

sharks[4] Outputnil

Finding the next available index in an array is error-prone and takes extra time. Avoid errors by using the push method, which adds an element to the end of an array:

sharks.push("Thresher") print sharks Output["Hammerhead", "Great White", "Tiger", "Whale", nil, "Whale", "Thresher"]

You can also use the Tutorial Series: How To Code in Ruby

Ruby is a popular object-oriented programming language. You can use Ruby to write anything from simple scripts to complex web applications. Open your favorite text editor and follow these tutorials to start exploring Ruby.

RubyDevelopmentBrowse Series: 11 articles1/11 How To Install Ruby and Set Up a Local Programming Environment on Ubuntu 22.04 2/11 How To Install Ruby on Rails with rbenv on Ubuntu 22.04 3/11 How To Write Your First Ruby Program About the authorsDefault avatarBrian Hogan

author

Default avatarTony Tran

author

Still looking for an answer?Ask a questionSearch for more helpWas this helpful? Leave a comment

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to CommentCreative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3